package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

//    支付超时，自动取消订单
    @Scheduled(cron = "59 * * * * *")
    public void task(){
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(15);
        Integer pendingPayment = Orders.PENDING_PAYMENT;
        List<Orders> orders = orderMapper.getByTimeAndStatus(pendingPayment, localDateTime);
        if (orders!=null && orders.size()>0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时，订单已取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

//自动完成一小时前下单的订单
    @Scheduled(cron = "0 * * * * *")
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        List<Orders> orders = orderMapper.getByTimeAndStatus(status, time);
        if (orders!=null && orders.size()>0) {
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }
}
